package com.tange.module.device.feature;

import android.content.Context;

import com.tange.base.toolkit.FileUtil;

import java.io.File;
import java.lang.reflect.Method;

import io.objectbox.Box;
import io.objectbox.BoxStore;
import io.objectbox.android.AndroidObjectBrowser;

/**
 * Describe:
 * Created by Rance Rang on 2019/5/10.
 * <p>
 * Copyright (c) Tange.Inc All rights reserved.
 */
public class DeviceFeatureObjectBox {
    private static BoxStore boxStore;

    public static void init(Context context) {

        String dbName = "app_device_feature";
        try {
            boxStoreBuilder(context);
        } catch (Exception e) {
            String path = getAndroidFilesDir(context);
            FileUtil.deleteDirectory(path);
            boxStoreBuilder(context);
        }

        if (BuildConfig.DEBUG) {
            new AndroidObjectBrowser(boxStore).start(context);
        }
    }
    private  static void boxStoreBuilder(Context context){
        String dbName = "app_device_feature";
        boxStore = MyObjectBox.builder()
                .androidContext(context).name(dbName)
                .maxReaders(256)
                .build();
    }
    public static String getAndroidFilesDir(Context context) {
        try {
            Method getFilesDir = context.getClass().getMethod("getFilesDir");
            File filesDir = (File) getFilesDir.invoke(context);
            if (filesDir == null) {
                // Race condition in Android before 4.4: https://issuetracker.google.com/issues/36918154 ?
                System.err.println("getFilesDir() returned null - retrying once...");
                filesDir = (File) getFilesDir.invoke(context);
            }
            if (filesDir != null) {
                return new File(filesDir, "objectbox").getAbsolutePath();
            }

        } catch (Exception ignored) {

        }
        return null;
    }

    public static DeviceFeature queryDeviceFeature(String uuid){
        if (getDeviceFeature()==null)return null;
        return  getDeviceFeature().query().equal(DeviceFeature_.uuid, uuid).build().findFirst();
    }

    public static Box<DeviceFeature> getDeviceFeature() {
        if (boxStore == null) return null;
        return boxStore.boxFor(DeviceFeature.class);
    }
}
